import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;

public class ScriptExecutor {
    public static void main(final String args[]) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine scriptEngine = manager.getEngineByName("js");
        System.out.println(scriptEngine.eval(new FileReader("scripts/example1.js")));

        Bindings bindings = scriptEngine.createBindings();
        scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        bindings.put("executed", Boolean.FALSE);
        String script = "" +
                "importPackage(java.util);" +
                "if (!executed) {" +
                "executed = true;" +
                "var random = new Random();" +
                "result = random.nextInt(x);" +
                "}";
        scriptEngine.put("x", 5);
        System.out.println(scriptEngine.eval(script));
        System.out.println(bindings.get("executed"));
    }
}